import re
import os

def getNet(*path)->dict[str, list[tuple[str, int,str]]]:
    if len(path)==1:
        path=path[0]
        filepaths= [f'{path}/{filename}' for filename in os.listdir(path) if filename.startswith("pstxnet")]
    else:
        filepaths= [filepath for filepath in path if os.path.basename(filepath).startswith("pstxnet")]
    netmap = {}
    # 取最新的信息
    filepath = max(filepaths)
    with open(filepath, 'r', encoding='utf-8') as f:
        rows = f.readlines()
    i = 0
    while i < len(rows):
        if rows[i].startswith('NET_NAME'):
            i+=1
            net = rows[i].strip().strip("'")
            netmap[net] = []
        elif rows[i].startswith('NODE_NAME'):
            name, point = rows[i].strip('NODE_NAME').strip().split()
            mark = rows[i+2].split("'")[1]
            try:
                point = int(point)
            except:
                point = point
            netmap[net].append((name, point, mark))
        i+=1
    return netmap
    
def getInfoMap(*path):
    if len(path)==1:
        path=path[0]
        prtpaths= [f'{path}/{filename}' for filename in os.listdir(path) if filename.startswith("pstxprt")]
        chippaths= [f'{path}/{filename}' for filename in os.listdir(path) if filename.startswith("pstchip")]
    else:
        prtpaths= [filepath for filepath in path if os.path.basename(filepath).startswith("pstxprt")]
        chippaths= [filepath for filepath in path if os.path.basename(filepath).startswith("pstchip")]
    filepath = max(prtpaths)
    with open(filepath, 'r', encoding='utf-8') as f:
        prts:list = f.readlines()
    filepath = max(chippaths)
    with open(filepath, 'r', encoding='utf-8') as f:
        chips:list = f.readlines()
    prts_map:dict = {}
    i = 0
    while i< len(prts):
        if prts[i].startswith('PART_NAME'):
            rer = re.search(r"([^ ]+?) '(.+?)':;",prts[i+1])
            assert rer, prts[i+1]
            name, key = rer.groups()
            prts_map[name] = key
            i+=1
        i+=1
    chips_map:dict = {}
    i = 0
    while i< len(chips):
        if chips[i].startswith('primitive'):
            rer = re.search(r"primitive '(.+?)';",chips[i])
            assert rer, chips[i]
            key = rer.group(1)
            chips_map[key] = {}
            i+=1
        elif chips[i].startswith('    PART_NAME='):
            rer = re.search(r"PART_NAME='(.+?)';",chips[i])
            assert rer, chips[i]
            chips_map[key]['part_name'] = rer.group(1)
            i+=1
        elif chips[i].startswith('    VALUE='):
            rer = re.search(r"VALUE='(.+?)';",chips[i])
            assert rer, chips[i]
            chips_map[key]['value'] = rer.group(1)
            i+=1
        i+=1
    info = {name: chips_map.get(key, {}) for name, key in prts_map.items()}
    return info
      